package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;


    //1.添加菜品
    @PostMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)
    public R save(@RequestBody DishDto disDto){
        //1.添加菜品信息dish
        dishService.saveDisWithFlavor(disDto);

        //2.添加菜品口味信息dish_flavor



        return  R.success("添加成功");
    }

    //2.显示菜品,分页查询
    @GetMapping("page")
    public R<Page<DishDto>> page( Long page, Long pageSize,String name){

        Page<DishDto> pageInfo = dishService.pageDishDto(page,pageSize,name);

       return R.success(pageInfo);

    }


    /**
     * 批量删除
     */
    @DeleteMapping
    public R<String> deleteByIds(Long[] ids) {
        //批量删除，需要自己定义业务逻辑（菜品状态为启售的不能删除）
        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 启用，停用
     */
    @PostMapping("status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, Long[] ids) {
        //批量修改状态
        // update dish set status=? where id in ( ids )
        dishService.lambdaUpdate()
            .set(Dish::getStatus, status) //修改值
            .in(Dish::getId, ids)       //条件部分
            .update();                  //更新操作
        return R.success("修改成功");
    }

    /**
     * 根据id查询菜品详情信息（包含多个口味）
     * 确定：返回一个对象 DishDto = Dish  +  List<DishFlavor>
     */
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getDishByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)
    public R update(@RequestBody DishDto dishDto) {
        //保存菜品，菜品口味数据
        dishService.updateDishWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /**
     * 根据 category_id或者 菜品名称 查询菜品列表
     */
    @GetMapping("list")
    @Cacheable(cacheNames = "dish",key = "#categoryId + '_' +#name",unless = "#result.data.size()<=0")
    public R<List<DishDto>> list(Long categoryId,String name){
        //查询数据库 select * from dish where satus = 1 and category_id ?
//        List<Dish> list = dishService.lambdaQuery()
//            .eq(Dish::getStatus,1)
//            .eq(categoryId != null,Dish::getCategoryId, categoryId)
//            .like(StringUtils.isNotBlank(name),Dish::getName, name)
//            .list();
        String redisKey = "dish_" + categoryId + "_" +name;
        redisKey = DigestUtils.md5DigestAsHex(redisKey.getBytes());

        //redis的数据类型，采用string
        List<DishDto> redisData = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        if(redisData != null){
            //不为空说明取到菜品数据，返回给R.success
            return R.success(redisData);
        }
            //缓存中没有数据，需要查询数据库，并将其存入redis中
        List<DishDto> dishDtoList = dishService.listDishDto(categoryId,name);
        redisTemplate.opsForValue().set(redisKey,dishDtoList,30, TimeUnit.MINUTES);
        return R.success(dishDtoList);






    }
}


